﻿using System.Web.Mvc;
using Web.Areas.Admin.Lib;
using Models;
using System.Linq;
using System;

namespace Web.Areas.Admin.Controllers
{
    public class BaseController : Controller
    {
        /// <summary>
        /// 在执行操作方法之前由 ASP.NET MVC 框架调用。(权限过滤)
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //获取当前地址
            var url = "/" + filterContext.RouteData.Values["controller"].ToString().ToLower() + "/" + filterContext.RouteData.Values["action"].ToString().ToLower();

            //判断是否判断登陆
            if (url == "/account/logon" || url == "/account/logout")
            {

            }
            else
            {
                if ((Account.ID < 1 || Account.GetAccount == null))
                {
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.Write("<script>alert('登录超时，请重新登录！');top.location.href='/account/logon';</script>");
                    filterContext.HttpContext.Response.End();
                }
                else
                {
                }
            }

            base.OnActionExecuting(filterContext);

        }

        protected override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                //filterContext.Exception = null;
                filterContext.ExceptionHandled = true;
                filterContext.Result = Json(new
                {
                    status = false,
                    errmsg = filterContext.Exception != null ? filterContext.Exception.Message : "系统异常，请稍后再试！",
                }, JsonRequestBehavior.AllowGet);
            }

            var e = filterContext.Exception;
            if (!filterContext.ExceptionHandled)
            {
                //filterContext.Exception = null;
                filterContext.Result = Redirect("/mobile/home/systemerror?msg=" + filterContext.Exception.Message);
                filterContext.ExceptionHandled = true;
            }
            base.OnException(filterContext);
        }

        /// <summary>
        /// 返回错误消息
        /// </summary>
        /// <param name="errmsg"></param>        
        /// <returns></returns>
        protected JsonResult ErrorMsg(string errmsg)
        {
            return this.ErrorMsg<string>(errmsg, null);
        }

        /// <summary>
        /// 返回错误消息
        /// </summary>
        /// <param name="errmsg"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        protected JsonResult ErrorMsg<T>(string errmsg, T data)
        {
            return Json(new
            {
                status = false,
                errmsg = errmsg,
                data = data
            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 返回成功消息
        /// </summary>                
        /// <returns></returns>
        protected JsonResult SuccessMsg()
        {
            return this.SuccessMsg<string>(null);
        }

        /// <summary>
        /// 返回成功消息
        /// </summary>        
        /// <param name="data">返回的数据</param>
        /// <returns></returns>
        protected JsonResult SuccessMsg<T>(string errmsg, T data)
        {
            return Json(new
            {
                status = true,
                errmsg = errmsg,
                data = data
            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 返回成功消息
        /// </summary>        
        /// <param name="data">返回的数据</param>
        /// <returns></returns>
        protected JsonResult SuccessMsg<T>(T data)
        {
            return Json(new
            {
                status = true,
                errmsg = "ok",
                data = data
            }, JsonRequestBehavior.AllowGet);
        }

        #region 分页信息

        /// <summary>
        /// 默认当前页面是第一页
        /// </summary>
        public int PageIndex
        {
            get
            {
                string pageindex = System.Web.HttpContext.Current.Request.QueryString["pageindex"];
                int p;
                if (!int.TryParse(pageindex, out p))
                {
                    p = 1;
                }

                return p;
            }
        }

        /// <summary>
        /// 默认每页显示5条信息
        /// </summary>
        public virtual int PageSize
        {
            get
            {
                string pagesize = System.Web.HttpContext.Current.Request.QueryString["pagesize"];
                int p;
                if (!int.TryParse(pagesize, out p))
                {
                    p = 10;
                }

                return p;
            }
        }

        public string Order
        {
            get
            {
                string order = System.Web.HttpContext.Current.Request.QueryString["order"];
                return string.IsNullOrWhiteSpace(order) ? "ID" : order;
            }
        }

        public string By
        {
            get
            {
                string by = System.Web.HttpContext.Current.Request.QueryString["by"];
                return string.IsNullOrWhiteSpace(by) ? "DESC" : by;
            }
        }
        #endregion

        public bool ValidFileType(string fileName, string fileType)
        {
            var valid = false;
            var allowedFileTips = "";
            string[] allowExtension = new string[] { };

            switch (fileType)
            {
                case "excel":
                    allowExtension = new string[] { ".xlsx", ".xls" };
                    break;
            }

            var fileExtension = fileName.Substring(fileName.LastIndexOf(".")).ToLower(); ;  //文件名
            int j = 0;
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (fileExtension == allowExtension[i])
                {
                    valid = true;
                    break;
                }
            }

            return valid;
        }
        public ActionResult CheckFileType(string filePath, string fileType)
        {
            if (filePath.Contains("//:"))
            {
                // 将图片路径转化为本地路径
                var domain = System.Configuration.ConfigurationSettings.AppSettings["SiteDomain"];
                var path = System.Configuration.ConfigurationSettings.AppSettings["SitePath"];
                filePath = filePath.Replace(domain, path);
            }

            var valid = false;
            var allowedFileTips = "";
            string[] allowExtension = new string[] { };

            switch (fileType)
            {
                case "excel":
                    allowExtension = new string[] { ".xlsx", ".xls" };
                    allowedFileTips = "文件格式有误，只能上传.xlsx/.xls文件！";
                    break;
            }

            //取得文件的扩展名,并转换成小写
            if (System.IO.File.Exists(filePath))
            {
                return ErrorMsg("判断文件类型：找不到文件，请确认！");
            }

            string fileExtension = System.IO.Path.GetExtension(filePath).ToLower();
            int j = 0;
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (fileExtension == allowExtension[i])
                {
                    valid = true;
                    break;
                }
            }

            if (valid)
                return SuccessMsg();
            return ErrorMsg(allowedFileTips);
        }
    }
}
